package com.crawler.waf.exceptions.support;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
import org.springframework.util.ClassUtils;

import com.crawler.waf.o2o.JacksonCustomObjectMapper;
/**
 * 转换器获取工具类，根据类加载器中所加载的解析数据类型jar包，进行判断是否支持某种的消息转换。并且通过此类可以进行捕获。
 *
 */
public abstract class HttpMessageConverterUtils {

    private static final ClassLoader CLASSLOADER = HttpMessageConverterUtils.class.getClassLoader();

    /**
     * 判断ClassPath中是否有 JAXB binder 被加载{@link javax.xml.bind.Binder}<br>
     */
    public static boolean isJaxb2Present() {
        return ClassUtils.isPresent("javax.xml.bind.Binder", CLASSLOADER);
    }

    /**
     * 判断ClassPath中是否有Jackson 2.x的包被加载<br>
     * {@link com.fasterxml.jackson.databind.ObjectMapper},<br>
     * {@link com.fasterxml.jackson.core.JsonGenerator} <br>
     */
    public static boolean isJackson2Present() {
        return ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", CLASSLOADER) &&
                ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", CLASSLOADER);
    }

    /**
     * 判断ClassPath中是否有Jackson 2.x的包被加载<br>
     *  {@link org.codehaus.jackson.map.ObjectMapper},<br>
     * {@link org.codehaus.jackson.JsonGenerator} <br>
     */
    public static boolean isJacksonPresent() {
        return ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", CLASSLOADER) &&
                ClassUtils.isPresent("org.codehaus.jackson.JsonGenerator", CLASSLOADER);
    }

    /**
     * 返回消息转换器 {@link HttpMessageConverter} 实例:
     */
    public static List<HttpMessageConverter<?>> getDefaultHttpMessageConverters() {

        List<HttpMessageConverter<?>> converters = new ArrayList<>();

        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        stringConverter.setWriteAcceptCharset(false); // See SPR-7316

        converters.add(new ByteArrayHttpMessageConverter());
        converters.add(stringConverter);
        converters.add(new ResourceHttpMessageConverter());

        if (isJaxb2Present()) {
            converters.add(new Jaxb2RootElementHttpMessageConverter());
        }
        if (isJackson2Present()) {
        	MappingJackson2HttpMessageConverter convert = new MappingJackson2HttpMessageConverter();
        	convert.setObjectMapper(new JacksonCustomObjectMapper());
            converters.add(convert);

        }
        return converters;
    }
}
